#include "accoutmanager.h"
#include <QuaZip/JlCompress.h>
#include <QMessageBox>
#include <QSettings>
#include <QFile>

AccoutManager::AccoutManager(QObject *parent) :
    QObject(parent)
{
    _uploader = new UpLoader(parent);
    _downloader = new DownLoader(parent);

    connect(_uploader, SIGNAL(progress(qint64,qint64)), parent, SIGNAL(progress(qint64,qint64)));
    connect(_uploader, SIGNAL(started()), parent, SLOT(uploadStarted()));
    connect(_uploader, SIGNAL(authFinished(bool,QString)), parent, SLOT(authFinished(bool,QString)));
    connect(_uploader, SIGNAL(finished(bool,bool,QString)), parent, SLOT(uploadFinished(bool,bool,QString)));

    connect(_downloader, SIGNAL(started(QString,qint64,QString)), parent, SLOT(downloadStarted(QString,qint64,QString)));
    connect(_downloader, SIGNAL(progress(qint64,qint64)), parent, SIGNAL(downloadProgress(qint64,qint64)));
    connect(_downloader, SIGNAL(finished(QString,bool,bool)), parent, SLOT(downloadFinished(QString,bool,bool)));

    QDir _dir("./");
    if(!_dir.exists("tmZip")){
        _dir.mkdir("tmZip");
    }else{
        QDir tmp("./tmZip/");
        QStringList filters;
        filters << "*.zip" << "*.part";
        tmp.setNameFilters(filters);
        QStringList zips = tmp.entryList(filters);
        for (int i = 0; i < zips.size(); ++i)
        {
            QFile p(tmp.absoluteFilePath(zips[i]));
            p.remove();
        }

    }
    QSettings settings(QSettings::UserScope, "Microsoft", "Windows");
    settings.beginGroup("CurrentVersion/Explorer/Shell Folders");
    DestDir = settings.value("Personal").toString()+"\\My Games\\Runic Games\\Torchlight 2\\";
    //DestDir = settings.value("Personal").toString()+"\\My Games\\Runic Games\\Test 2\\";
    TestLocked();
    cleanDir(DestDir);
}

void AccoutManager::Extract()
{

    JlCompress zp;
    zp.extractDir("tmZip/"+_user+".zip",DestDir);
}

void AccoutManager::Compress()
{

    QDir base(DestDir+"logs/");
    QStringList filters;
    filters << "*.txt";
    base.setNameFilters(filters);
    QStringList zips = base.entryList(filters);
    for (int i = 0; i < zips.size(); ++i)
    {
        QFile p(base.absoluteFilePath(zips[i]));
        p.remove();
    }
    QFile p(DestDir+"/Ogre.log");
    p.remove();
    JlCompress zp;
    zp.compressDir("tmZip/"+_user+".zip",DestDir,true);
}

void AccoutManager::LockSess()
{
    Extract();
    QFile file(QString(DestDir+_user+".Lock"));
    file.open(QIODevice::WriteOnly);
    file.write(_pass.toAscii().toBase64());
    file.close();
    QFile f("tmZip/"+_user+".zip");
    f.remove();
}

void AccoutManager::UnLockSess(bool hash)
{
    Compress();
    _uploader->upload("tmZip/"+_user+".zip", _pass, _user, hash);
    cleanDir(DestDir);
    _user="";
    _pass="";

}

void AccoutManager::Login(QString user, QString pass)
{
    _user=user;
    _pass=pass;
    _downloader->download(user,QString(pass.toAscii().toBase64()));
}

void AccoutManager::TestLocked()
{
    QDir dir(DestDir);
    QStringList filters;
    filters << "*.Lock";
    dir.setNameFilters(filters);
    QStringList lockuser = dir.entryList(filters);
    if(lockuser.count() >0)
    {
        QFile file(DestDir+lockuser[0]);
        file.open(QIODevice::ReadOnly);
        _pass = QString(file.readLine()).remove("\n");
        _user=QFileInfo(file).baseName();
        file.close();
        UnLockSess(false);
        return;
    }
    return;
}

bool AccoutManager::cleanDir(const QString &dirName, const bool &all)
{
    bool result = true;
    QDir dir(dirName);

    if (dir.exists(dirName)) {
        Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden  | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
            if (info.isDir()) {
                result = cleanDir(info.absoluteFilePath(),true);
            }
            else {
                if(info.baseName()!="local_settings")
                    result = QFile::remove(info.absoluteFilePath());
            }

            if (!result) {
                return result;
            }
        }
        if(all)
            result = dir.rmdir(dirName);
    }

    return result;
}
